package cn.edu.seu.ssny.controller.admin.system;

import cn.edu.seu.ssny.common.JsonResult;
import cn.edu.seu.ssny.controller.BaseController;
import cn.edu.seu.ssny.entity.*;
import cn.edu.seu.ssny.service.*;
import cn.edu.seu.ssny.service.specification.SimpleSpecificationBuilder;
import cn.edu.seu.ssny.service.specification.SpecificationOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/admin/equipment")
public class EquipmentController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(EquipmentController.class);


    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IEquipmentService equipmentService;
    @Autowired
    private IEquipmentTypeService equipmentTypeService;
    @Autowired
    private ISysClassService sysClassService;

    @RequestMapping(value = {"/", "/index/{id}"})
    public String index(@PathVariable Integer id, ModelMap map) {
        Project project = projectService.find(id);
        map.put("project", project);
        return "admin/equipment/index";
    }

    @RequestMapping(value = {"/list/{id}"})
    @ResponseBody
    public Page<Equipment> list(@PathVariable Integer id) {
        SimpleSpecificationBuilder<Equipment> builder = new SimpleSpecificationBuilder<Equipment>();
        builder.add("project", SpecificationOperator.Operator.eq.name(), projectService.find(id));
        Page<Equipment> page = equipmentService.findAll(builder.generateSpecification(), getPageRequest());
        return page;
    }

    @RequestMapping(value = {"/showDeviceList/{id}"})
    public String showDeviceList(@PathVariable Integer id, ModelMap map) {
        Equipment equipment = equipmentService.find(id);
        Project project = equipment.getProject();
        map.put("project", project);
        map.put("equipment", equipment);
        return "admin/device/equipment-device";
    }

    @RequestMapping(value = "/add/{id}", method = RequestMethod.GET)
    public String add(@PathVariable Integer id, ModelMap map) {
        List<EquipmentType> typeList = equipmentTypeService.findAll();
        Project project = projectService.find(id);
        List<SysClass> sysClasses = sysClassService.findAllByProjectId(Long.valueOf(id));
        map.put("sysClasses", sysClasses);
        //对应项目的
        map.put("project", project);
        map.put("typeList", typeList);
        return "admin/equipment/form";
    }

    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String edit(@PathVariable Integer id, ModelMap map) {
        Equipment equipment = equipmentService.find(id);
        List<EquipmentType> typeList = equipmentTypeService.findAll();
        Project project = equipment.getProject();
        List<SysClass> sysClasses = sysClassService.findAllByProjectId(Long.valueOf(project.getId()));
        map.put("sysClasses", sysClasses);
        map.put("project", project);
        map.put("equipment", equipment);
        map.put("typeList", typeList);
        return "admin/equipment/form";
    }


    @RequestMapping(value = {"/edit"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult edit(Equipment equipment, ModelMap map, HttpSession session) {
        String project_id = request.getParameter("project_id");
        String type_id = request.getParameter("type_id");

        Project project = projectService.find(Integer.parseInt(project_id));
        EquipmentType type = equipmentTypeService.find(Integer.parseInt(type_id));
        SysClass sysClass = null;
        String sysclass_id = request.getParameter("sysclass_id");
        if (sysclass_id != null && sysclass_id.trim().length() != 0) {
            Long sysClassId = Long.valueOf(sysclass_id);
            sysClass = sysClassService.findById(sysClassId);
        }
        try {
            equipment.setSysClass(sysClass);
            equipmentService.saveOrUpdate(equipment, (Enterprise) session.getAttribute("enterprise"), project, type);

        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult delete(@PathVariable Integer id, ModelMap map) {
        try {
            equipmentService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/deletems/{ids}", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult deletems(@PathVariable String ids, ModelMap map) {
        if (ids == null)
            return JsonResult.failure("删除失败");
        String[] idArray = ids.split("&");
        for (String id : idArray) {
            try {
                equipmentService.delete(Integer.parseInt(id));
            } catch (Exception e) {
                e.printStackTrace();
                return JsonResult.failure(e.getMessage());
            }
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/grant/{equipmentId}", method = RequestMethod.GET)
    public String grant(@PathVariable("equipmentId") Integer equipmentId,
                        ModelMap map, HttpSession session) {
        Equipment equipment = equipmentService.find(equipmentId);
        map.put("equipment", equipment);

        List<Device> deviceList = new ArrayList<>(equipment.getDevices());
        Collections.sort(deviceList);
        List<Integer> deviceIds = new ArrayList<Integer>();
        for (Device device : deviceList) {
            deviceIds.add(device.getId());
        }
        map.put("deviceIds", deviceIds);
        Project project = equipment.getProject();
        List<Device> devices = new ArrayList<>(project.getDevices());
        Collections.sort(devices);
        map.put("devices", devices);

        return "admin/equipment/grant";
    }

    @ResponseBody
    @RequestMapping(value = "/grant/{id}", method = RequestMethod.POST)
    public JsonResult grant(@PathVariable Integer id, String[] deviceIds, ModelMap map) {
        try {
            deviceService.setDevicesByEquipment(equipmentService.find(id), deviceIds);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

    @RequestMapping(value = "/display/{id}", method = RequestMethod.GET)
    public String display(@PathVariable Integer id, ModelMap map) {
        Equipment equipment = equipmentService.find(id);
        Project project = equipment.getProject();
        List<Equipment> equipments = equipmentService.findByProject(project);
        map.put("currEquipment", equipment);
        map.put("equipments", equipments);
        return "admin/equipment/display";
    }

    @RequestMapping(value = {"/display/edit"}, method = RequestMethod.POST)
    @ResponseBody
    public JsonResult displayEdit(Equipment equipment, ModelMap map, HttpSession session) {
        try {
            equipmentService.saveCoordinate(equipment);
        } catch (Exception e) {
            return JsonResult.failure(e.getMessage());
        }
        return JsonResult.success();
    }

}
